package algorithm;

import java.util.Arrays;

/**
 * 给你一个头结点为 head 的单链表和一个整数 k ，请你设计一个算法将链表分隔为 k 个连续的部分。
 *
 * 每部分的长度应该尽可能的相等：任意两部分的长度差距不能超过 1 。这可能会导致有些部分为 null 。
 *
 * 这 k 个部分应该按照在链表中出现的顺序排列，并且排在前面的部分的长度应该大于或等于排在后面的长度。
 *
 * 返回一个由上述 k 部分组成的数组。
 *
 * exp1：输入：head = [1,2,3], k = 5
 *      输出：[[1],[2],[3],[],[]]
 *
 * exp2： 输入：head = [1,2,3,4,5,6,7,8,9,10], k = 3
 *        输出：[[1,2,3,4],[5,6,7],[8,9,10]]
 */
public class 分隔链表 {

    public static class ListNode{
        private ListNode next;
        private int val;
        ListNode() {}
        ListNode(int val){this.val = val;}
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    '}';
        }
    }

    public static void main(String[] args) {

        ListNode head = new ListNode(1);
        ListNode head1 = new ListNode(2);
        ListNode head2 = new ListNode(3);
        ListNode head3 = new ListNode(4);
        ListNode head4 = new ListNode(5);
        ListNode head5 = new ListNode(6);
        ListNode head6 = new ListNode(7);
        ListNode head7 = new ListNode(8);
        ListNode head8 = new ListNode(9);
        ListNode head9 = new ListNode(10);

        head.next = head1;
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        head5.next = head6;
        head6.next = head7;
        head7.next = head8;
        head8.next = head9;
        head9.next = null;

        for (ListNode listNode : splitListToParts(head, 11)) {
            System.out.println(listNode);
        }


    }

    public static ListNode[] splitListToParts(ListNode head, int k) {

        if(head == null || k == 0){
            return null;
        }
        //求链表长度
        int count = 0;
        ListNode cur = head;
        while (cur!=null){
            cur = cur.next;
            count++;
        }

        //根据k进行对长度划分
        int[] array = splitLink(count , k);

        //切割
        ListNode [] res = new ListNode[k];
        cur  = head;

        for (int i = 0; i < array.length && cur != null; i++){
            res[i] = cur;
            for (int j = 0; j < array[i] - 1; j++){
                cur = cur.next;
            }
            ListNode next = cur.next;
            cur.next = null;
            cur = next;
        }
        return res;
    }

    public static int[] splitLink(int length , int k ){

       int number =  length/k;
       int model = length %k;
       int[] array = new int[k];
       for (int i = 0 ; i < k ; i ++){
           if(model > 0 ){
               array[i] = (number == 0 ? 0:number)  + 1;
               model--;
           }else{
               array[i] = (number == 0 ? 0:number);
           }
       }
       return array;
    }


}
